package guiLayer;
import guiLayer.extensions.OwnerExistExeption;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import modelLayer.Owner;
import controlerLayer.OwnerCtr;


public class CreaterOwner extends Creater {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Owner o;
	private Updater updater;
	/**
	 * Create the panel.
	 */
	public CreaterOwner(){
		panel_1.remove(cmb);
		panel_1.remove(lblCmb);
	}
	
	public CreaterOwner(final Owner o, final Updater updater) {
		panel_1.remove(cmb);
		panel_1.remove(lblCmb);

		this.o = o;
		this.updater = updater;
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				createOwner();
			}
		});
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(o != null){
					updater.closeMe(CreaterOwner.this);
				}else{
					clear();
				}
			}
		});
		
		
		lblItem3.setText("Phone");
		lblItem2.setText("Address");
		lblItem1.setText("Name");
		if(o == null){
			btnClear.setText("Clear");
			btnCreate.setText("Create");
			lblTitle.setText("Create Owner");
		}else if(o != null){
			btnClear.setText("Cancel");
			btnCreate.setText("Update");
			lblTitle.setText("Update Owner");
			txtItem1.setText(o.getName());
			txtItem2.setText(o.getAddress());
			txtItem3.setText("" + o.getPhoneNumber());
		}
	}

	protected void createOwner() {
		if(checkInput()){
			OwnerCtr oCtr = new OwnerCtr();
			String name = txtItem1.getText();
			String address = txtItem2.getText();
			int phoneNumber = Integer.parseInt(txtItem3.getText());
			if(o == null){
				try {
					oCtr.addOwner(name, address, phoneNumber);
					created(lblCreated, "Owner " + name + " created!");
					clear();
				} catch (OwnerExistExeption e) {
					error(lblCreated, e.getMessage());
				}
			}else if(o != null){
				o.setName(name);
				o.setAddress(address);
				o.setPhoneNumber(phoneNumber);
				updater.closeMe(this);
			}
		}
	}
	
	protected boolean checkInput(){
		boolean ret = true;
		
		if(txtItem3.getText().length() <= 0){
			error(lblErrorItem3, "Phone cant be empty");
			ret = false;
		}else{
			try{
				Integer.parseInt(txtItem3.getText());
			}catch(NumberFormatException e){
				error(lblErrorItem3, "Phone must be a number");
				ret = false;
			}
			
			lblErrorItem3.setText("");
		}
		
		if(txtItem1.getText().length() <= 0){
			error(lblErrorItem1, "Name cant be empty");
			ret = false;
		}else{
			lblErrorItem1.setText("");
		}
		
		if(txtItem2.getText().length() <= 0){
			error(lblErrorItem2, "Address cant be empty");
			ret = false;
		}else{
			lblErrorItem2.setText("");
		}
		
		return ret;
	}

	@Override
	protected void clear() {
		super.clear();
	}
	
}
